package org.rc.controller;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.rc.dto.CasePageDto;
import org.rc.dto.CaseQueryDto;
import org.rc.dto.PageDto;
import org.rc.dto.Res;
import org.rc.entity.Caze;
import org.rc.service.CaseLibraryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/case_library")
public class CaseLibraryController {

    @Value("${file.save.path}")
    private String fileSavePath;

    @Autowired
    private CaseLibraryService caseLibraryService;

    @PostMapping("/upload")
    public Res uploadFile(@RequestParam("file") MultipartFile file){
        if(null == file){
            return Res.failure("请选择上传到的文档！");
        }
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        if(!fileName.contains(".xls") || !fileName.contains(".xlsx")){
            return Res.failure("请上传excel格式文件");
        }
        String fullFilePath = fileSavePath + File.separator+fileName;
        InputStream inputStream = null;
        try{
            inputStream = file.getInputStream();
            File saveFile = new File(fullFilePath);
            if(saveFile.exists()){
                saveFile.delete();
            }
            FileUtils.copyInputStreamToFile(inputStream,saveFile);
        }catch (Exception e){
            log.error("文件写入磁盘失败，e--->",e);
        }finally {
            if(null != inputStream){
                try{
                    inputStream.close();
                }catch (Exception e){
                    log.error("关闭流失败,e--->",e);
                }

            }
        }
        //全量导入，删除之前入库的数据
        caseLibraryService.removeAllRecords();
        List<Caze> cazes = new ArrayList<>();
        ExcelReader reader =null;
        try{
            reader = ExcelUtil.getReader(fullFilePath);
            List<Map<String, Object>> sheet = reader.readAll();
            if(CollectionUtils.isEmpty(sheet)){
                return Res.failure("文件内容为空");
            }
            for (Map<String, Object> row : sheet) {
                Caze caze = new Caze();
                if(null!=row.get("案件类型")){
                    caze.setCaseType(String.valueOf(row.get("案件类型")).trim());
                }
                if(null!=row.get("案件名称")){
                    caze.setCaseName(String.valueOf(row.get("案件名称")));
                }
                if(null!=row.get("案件详情")){
                    caze.setCaseDetail(String.valueOf(row.get("案件详情")));
                }
                cazes.add(caze);
            }
            caseLibraryService.addCaseLibrary(cazes);
        }catch (Exception e){
            log.error("读取excel失败，e--->",e);
            return Res.failure("读取excel失败");
        }finally {
            assert reader != null;
            reader.close();
        }
        return Res.success("数据导入成功");
    }


    @PostMapping("/page")
    public Res geteCasePage(@RequestBody CasePageDto casePageDto){
        return Res.success(PageDto.of(caseLibraryService.getCasePage(casePageDto)));
    }

    @GetMapping("/{id}")
    public Res getCaseDetailById(@PathVariable("id") Long id){
        return Res.success(caseLibraryService.getDetailById(id));
    }

    @GetMapping("/allTypes")
    public Res getAllCaseType(){
        List<Caze> cases = caseLibraryService.getAllTypes();
        if(CollectionUtils.isEmpty(cases)){
            return Res.success(new ArrayList<>());
        }
        return Res.success(cases.stream().map(Caze :: getCaseType).collect(Collectors.toList()));
    }

    @PostMapping("/byType")
    public Res getCasesByType(@RequestBody CaseQueryDto caseQueryDto){
        return Res.success(caseLibraryService.getCasesByType(caseQueryDto.getType()));
    }

}
